<?php
/**
 * Created by PhpStorm.
 * User: laowang
 * Date: 2018/5/9
 * Time: 下午4:34
 */

namespace app\home\controller;
use app\home\model\WechatUser;
use app\home\model\Homework as HomeworkModel;
use app\home\model\Xuexiao;
use app\home\model\TeacherNotes;
use com\wechat\TPWechat;
use think\Config;
/**
 * Class Homework
 * @package app\home\controller
 * 作业提交
 */
class Homework extends Base
{
    public function index(){
        $userId = input('openid',session('userId'));
        $User = WechatUser::where(['openid' => $userId])->field('review_status,role,subscribe,openid,headimgurl,school_id,name,nickname')->find();
        if ($User['review_status'] == 0 || $User['role'] == 1 || $User['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        $msg = array();
        $msg['openid'] = $User['openid'];
        $msg['header'] = $User['headimgurl'];  // 头像
        $msg['name'] = $User['name'] ? $User['nickname'] : $User['name'];
        $msg['xuexiao'] = get_school($User['school_id']);
        if (input('openid')){
            $this->assign('is',1);
        }else{
            $this->assign('is',0);
        }
        if (IS_POST){
            $year = input('year');
            $month = input('month');
            //只选取年份，默认为所有
            if($year && ($month == 0)) {
                $info = array(
                    "FROM_UNIXTIME(create_time,'%Y')" => $year,
                    'openid' => $userId,
                    'status' => 0
                );
                $all = HomeworkModel::where($info)->order('id desc')->select();
                //重组用key值分组
                $list = array();
                foreach ($all as $value) {
                    switch ($value['class']){
                        case 1:
                            $pre = "英语词汇";
                            break;
                        case 2:
                            $pre = "英语精翻";
                            break;
                        case 3:
                            $pre = "英语精听";
                            break;
                        case 4:
                            $pre = "数学题";
                            break;
                        case 5:
                            $pre = "国二office";
                            break;
                        case 6:
                            $pre = "作文批阅";
                            break;
                        default:
                            $pre = "暂无";
                            break;
                    }
                    $k = date("n",$value['create_time']);
                    if (strip_tags($value['content'])){
                        $title = "【{$pre}】".strip_tags($value['content']);
                    }else{
                        $title = "【{$pre}】".'作业提交，点击查看详情';
                    }
                    $scan = 0;
                    $Note = TeacherNotes::where(['sid' => $value['id']])->value('create_time');
                    if ($value['result'] || !empty($Note)){
                        $scan = 1;
                    }
                    $list[$k][] = array('id' => $value['id'],'day' => date("d", $value['create_time']),'title' => $title,'scan' => $scan);
                }
                krsort($list);
            }else{
                if ($month < 10){
                    $month = "0".$month;
                }
                $info = array(
                    "FROM_UNIXTIME(create_time,'%Y%m')"  => $year.$month,
                    'openid' => $userId,
                    'status' => 0
                );
                $all = HomeworkModel::where($info)->order('id desc')->select();
                //重组用key值分组
                $list = array();
                foreach($all as $value){
                    switch ($value['class']){
                        case 1:
                            $pre = "英语词汇";
                            break;
                        case 2:
                            $pre = "英语精翻";
                            break;
                        case 3:
                            $pre = "英语精听";
                            break;
                        case 4:
                            $pre = "数学题";
                            break;
                        case 5:
                            $pre = "国二office";
                            break;
                        case 6:
                            $pre = "作文批阅";
                            break;
                        default:
                            $pre = "暂无";
                            break;
                    }
                    $k = date("n",$value['create_time']);
                    if (strip_tags($value['content'])){
                        $title = "【{$pre}】".strip_tags($value['content']);
                    }else{
                        $title = "【{$pre}】".'作业提交，点击查看详情';
                    }
                    $scan = 0;
                    $Note = TeacherNotes::where(['sid' => $value['id']])->value('create_time');
                    if ($value['result'] || !empty($Note)){
                        $scan = 1;
                    }
                    $list[$k][] = array('id' => $value['id'],'day' => date("d", $value['create_time']),'title' => $title,'scan' => $scan);
                }
                krsort($list);
            }
            return $this->success('','',$list);
        }else{
            $msg['year'] = date('Y',time());
            $msg['mouth'] = date('m',time());
            //获取全部共同数据年份
            $years = HomeworkModel::all(function($query){
                $query->group("FROM_UNIXTIME(create_time,'%Y')")->field("FROM_UNIXTIME(create_time,'%Y') as year");
            });
            array_shift($years);
            $this->assign('years',$years);
        }
        if ($msg['mouth'] < 10){
            $msg['mouth'] = substr($msg['mouth'],1);
        }
        $this->assign('msg',$msg);
        return $this ->fetch();
    }
    //作业详情
    public function detail(){
        $id = input('id/d');
        $openid = input('openid');
        $userId = session('userId');
        $User = WechatUser::where(['openid' => $userId])->field('role,review_status,subscribe')->find();
        if ($User['review_status'] == 0 || $User['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        $msg = HomeworkModel::where(['id' => $id])->find();
        if (empty($msg)){
            $this->redirect('Journal/del');
        }
        $Users = WechatUser::where(['openid' => $openid])->find();
        if ($User['role'] == 1){
            // 老师
            $this->assign('is',1);
        }else{
            // 学生
            $this->assign('is',0);
        }
        $msg['header'] = $Users['headimgurl'];  // 头像
        if (empty($Users['name'])){
            $msg['name'] = $Users['nickname'];
        }else{
            $msg['name'] = $Users['name'];  // 姓名
        }
        if (empty($msg['result'])){
            $Note = TeacherNotes::where(['sid' => $id])->find();
            if (!empty($Note)){
                $msg['result'] = $Note['result'];
            }
        }
        $msg['xuexiao'] = '暂无';
        if ($Users['school_id']){
            $school = Xuexiao::where('dx_id',$Users['school_id'])->find();
            if ($school){
                $msg['xuexiao'] = iconv("gbk", "utf-8//ignore", $school['dx']);
            }
        }
        switch ($msg['class']){
            case 1:
                $msg['name'] = "英语词汇";
                break;
            case 2:
                $msg['name'] = "英语精翻";
                break;
            case 3:
                $msg['name'] = "英语精听";
                break;
            case 4:
                $msg['name'] = "数学题";
                break;
            case 5:
                $msg['name'] = "国二office";
                break;
            case 6:
                $msg['name'] = "作文批阅";
                break;
            default:
                $msg['name'] = "暂无";
                break;
        }
        $this->assign('msg',$msg);
        return $this ->fetch();
    }
    // 发布页面
    public function publish(){
        $userId = session('userId');
        $User = WechatUser::where(['openid' => $userId])->field('subscribe,review_status,openid,role')->find();
        if ($User['review_status'] == 0 || $User['role'] == 1 || $User['subscribe'] == 0){
            $this->redirect('Journal/null');
        }
        $this->jssdk();
        $Wechat = new TPWechat(Config::get('party'));
        if (IS_POST){
            $data = input('post.');
            $images = '';
            if (!empty($data['pic'])){
                foreach ($data['pic'] as $value){
                    $pic = $Wechat->getMedia($value);
                    $url = "./uploads/download/images/".time().uniqid().".jpg";
                    $myfile = fopen($url, "w+");
                    fwrite($myfile, $pic);
                    fclose($myfile);
                    $images .= '<img src="/DDDeducation/public'.substr($url,1).'" alt="" width="400" height="200" border="0" />';
                }
            }
            $content = $data['con'].'<br/>'.$images;
            $info = array(
                'openid' => $userId,
                'content' => $content,
                'class' => $data['class'],
                'create_time' => $data['time'],
                'status' => 0,
                'type' => 0
            );
            $before = strtotime(date('Y-m-d 00:00:00',$data['time']));
            $now = strtotime(date('Y-m-d 23:59:59',$data['time']));
            $Summary = new HomeworkModel();
            $journal = $Summary->where(['openid' => $userId,'status' => 0,'create_time' => ['between',[$before,$now]]])->find();
            if(empty($journal)){
                $info['type'] = 1;
                WechatUser::where('openid',$userId)->setInc('score',1);
            }
            $res = $Summary->save($info);
            if ($res){
                return $this->success('提交成功');
            }else{
                return $this->error('提交失败');
            }
        }else{
            $month_final = mktime(23,59,59,date('m'),date('d'),date('Y'));
            $arr = [];
            while (count($arr) <= 5){
                $arr[] = $month_final;
                $month_final -= 24 * 3600;
            }
            $this->assign('now',time());
            $this->assign('arr',$arr);
            return $this->fetch();
        }
    }
    // 批语 提交
    public function sign(){
        $userId = session('userId');
        $result = input('result');
        $id = input('id');
        if (empty($id)){
            return $this->error('系统参数错误');
        }
        $res = HomeworkModel::where('id',$id)->update(['result' => $result]);
        if ($res){
            $teacher = TeacherNotes::where(['sid' => $id,'openid' => $userId])->find();
            if ($teacher){
                // 更新
                TeacherNotes::where(['id' => $teacher['id']])->update(['result' => $result,'create_time' => time()]);
            }else{
                // 添加
                $Model = new TeacherNotes();
                $Model->save(['sid' => $id,'openid' => $userId,'result' => $result,'create_time' => time()]);
            }
            $openid = HomeworkModel::where('id',$id)->value('openid');
            $con = '【批阅更新了】
你的作业已评阅，<a href="http://mp.csppat.com/DDDeducation/public/index.php/home/Homework/detail/openid/'.$openid.'/id/'.$id.'">点我</a>可快速查看老师的批注哦~~';
            $send = array(
                "content" => $con
            );
            $Wechat = new TPWechat(Config::get('party'));
            $data = array(
                "touser" => $openid,
                "msgtype" => "text",
                "text" => $send
            );
            $Wechat->sendCustomMessage($data);
            return $this->success('批阅成功');
        }else{
            return $this->error('批阅失败，内容未更新！');
        }
    }
    public function del(){
       $id = input('id');
       if (empty($id)){
           return $this->error('系统参数错误');
       }
        $res = HomeworkModel::where(['id' => $id])->delete();
        if ($res){
            $ress = TeacherNotes::where(['sid' => $id])->find();
            if (!empty($ress)){
                TeacherNotes::where(['sid' => $id])->delete();
            }
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败');
        }
    }
}